package com.tuanzi.loan.web.bean.xhh.settlementsystem;

import com.google.common.collect.Lists;
import com.starbaba.model.utils.JSONUtils;
import com.tuanzi.loan.business.entity.xhh.settlementsystem.XhhSettlementBill;
import com.tuanzi.loan.business.entity.xhh.settlementsystem.XhhSettlementIncome;
import com.tuanzi.loan.business.entity.xhh.settlementsystem.XhhSettlementPrepay;
import com.tuanzi.loan.business.service.xhh.settlementsystem.XhhRemainType;
import com.tuanzi.loan.business.service.xhh.settlementsystem.XhhSettlementBillService;
import com.tuanzi.loan.business.service.xhh.settlementsystem.XhhSettlementIncomeService;
import com.tuanzi.loan.business.service.xhh.settlementsystem.XhhSettlementPrepayService;
import com.tuanzi.loan.core.aspect.Debug;
import com.tuanzi.loan.web.configuration.JSFWorkflowBean;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.primefaces.model.DefaultStreamedContent;
import org.primefaces.model.StreamedContent;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.faces.bean.ViewScoped;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
import java.util.List;

import static com.tuanzi.loan.business.constants.DictionaryCode.*;

/**
 * @author caiwanlin
 * @create 2018-08-16 20:36
 */
@Data
@Debug
@Slf4j
@Component
@ViewScoped
@EqualsAndHashCode(callSuper = true)
public class XhhBillCheckBean extends JSFWorkflowBean<XhhSettlementBill> {

    @Autowired
    private XhhSettlementBillService xhhSettlementBillService;

    @Autowired
    private XhhSettlementIncomeService xhhSettlementIncomeService;

    @Autowired
    private XhhSettlementPrepayService xhhSettlementPrepayService;

    private List<XhhSettlementIncome> incomeList;

    private List<XhhSettlementPrepay> prepayList;

    @PostConstruct
    private void init() {
        if (task != null){
            Long billId = Long.parseLong(task.getBusinessKey().split(":")[1]);
            $ = xhhSettlementBillService.findOne(billId);
            String detailList = $.getDetailList();
            if ($.getRecordType() == XhhRemainType.EXPEND.index){//消耗开票
                if (StringUtils.isNotBlank(detailList)){
                    incomeList = JSONUtils.fromJsonArrayNew(detailList, XhhSettlementIncome.class);
                }
                else {
                    incomeList = Lists.newArrayList();
                }
            }
            else if ($.getRecordType() == XhhRemainType.PREPAY.index){
                if (StringUtils.isNotBlank(detailList)){
                    prepayList = JSONUtils.fromJsonArrayNew(detailList, XhhSettlementPrepay.class);
                }
                else {
                    prepayList = Lists.newArrayList();
                }
            }
        }
    }

    @Override
    public void onSave() {

    }


    @Override
    public void validate() {

    }

    @Override
    public String onApprove() {
        super.onApprove();
        return redirect("/views/xhh/settlementsystem/bill/bill-workbench.xhtml");
    }

    @Override
    public String onCancel() {
        super.onCancel();
        return redirect("/views/xhh/settlementsystem/bill/bill-workbench.xhtml");
    }

    @Override
    public String onPass() {
        super.onPass();
        return redirect("/views/xhh/settlementsystem/bill/bill-workbench.xhtml");
    }

    @Override
    protected List<String> getDictionaryCodes() {
        return  Lists.newArrayList(XHH_SETTLEMENT_SPREAD_CHANNEL,XHH_SETTLEMENT_INCOME_TYPE,
                XHH_SETTLEMENT_SPREAD_MODE, XHH_COOPERATION_MODE, XHH_SETTLEMENT_CYCLE,
                XHH_SETTLEMENT_BILLING_CONTENT,XHH_SETTLEMENT_BILL_TYPE,XHH_SETTLEMENT_PAY_MODE);
    }

	public StreamedContent onDownloadAttachment(String type) {
		String urlPath;

		if (StringUtils.isBlank(type)) {
			if (StringUtils.isBlank($.getAttachmentUrl())) {
				return null;
			}

			urlPath = $.getAttachmentUrl();
		} else {
			if (StringUtils.isBlank($.getImgAttachmentUrl())) {
				return null;
			}

			urlPath = $.getImgAttachmentUrl();
		}

		String fileName = urlPath.substring(urlPath.lastIndexOf("/") + 1);
		InputStream stream = null;
		try {
			URL mediaUrl = new URL(urlPath);
			HttpURLConnection conn = (HttpURLConnection) mediaUrl.openConnection();
			conn.setDoOutput(true);
			conn.setRequestMethod("GET");
			stream = conn.getInputStream();
		} catch (MalformedURLException e) {
			log.error(e.getMessage(), e);
		} catch (ProtocolException e) {
			log.error(e.getMessage(), e);
		} catch (IOException e) {
			log.error(e.getMessage(), e);
		}
		return new DefaultStreamedContent(stream, null, fileName);
	}
}
